/* gcc -lrt */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>

#include "msgdata.h"

int main(int argc, char *argv[])
{
    char pathname[80];
    struct stat fileattr;
    key_t key;
    struct msg_struct data;
    long int msg_type;
    char buffer[TEXT_SIZE];
    int msqid, ret, count = 0;
    FILE *fp;
    pid_t childpid1, childpid2;

    if (argc < 2) {
        printf("Usage: ./a.out pathname\n");
        return EXIT_FAILURE;
    }
    strcpy(pathname, argv[1]);

    if (stat(pathname, &fileattr) == -1)
    {
        ret = creat(pathname, O_RDWR);
        if (ret == -1)
        {
            ERR_EXIT("creat()");
        }
        printf("shared file object created\n");
    }

    key = ftok(pathname, 0x27); /* project_id can be any nonzero integer */
    if (key < 0) {
        ERR_EXIT("ftok()");
    }

    printf("\nIPC key = 0x%x\n", key);

    msqid = msgget((key_t)key, 0666 | IPC_CREAT);
    if (msqid == -1) {
        ERR_EXIT("msgget()");
    }

    char *argv1[] = {" ", argv[1], 0};
    childpid1 = vfork();
    if (childpid1 < 0) {
        ERR_EXIT("msgthreadcon: 1st vfork()");
    } else if (childpid1 == 0) {
        execv("./msgsend.o", argv1); /* call shmproducer with filename */
    } else {
        childpid2 = vfork();
        if (childpid2 < 0) {
            ERR_EXIT("msgthreadcon: 2nd vfork()");
        } else if (childpid2 == 0) {
            execv("./msgrecv.o", argv1); /* call shmconsumer with filename */
        } else {
            wait(&childpid1);
            wait(&childpid2);
            if (msgctl(msqid, IPC_RMID, 0) == -1)
                perror("msgctl(IPC_RMID)");
        }
    }

    exit(EXIT_SUCCESS);
}
